#include "headfiles.h"

using namespace std;

bool readLastNLines(string &file_name, int n) {
    if (file_name.empty()) {
        cout << "Invalid file name." << endl;
        return false;
    }

    fstream fs;
    fs.open(file_name.c_str(), fstream::in);
    if (!fs.is_open()) {
        cout << "Open file " << file_name << " error!" << endl;
        return false;
    }

    vector<string *> str_vec;
    int i = 0;
    for (i = 0; i < n; i++) {
        string *tmp = new string();
        str_vec.push_back(tmp);
    }

    int index = 0;
    string str;
    while (getline(fs, str)) {
        if (str.empty()) {
            break;
        }
        *str_vec[index % n] = str;
        index++;
    }

    int start, str_num;
    if (index >= n) {
        start = index % n;
        str_num = n;
    }
    else {
        start = 0;
        str_num = index;
    }

    for (i = 0; i < str_num; i++) {
        index = (i + start) % n;
        cout << *str_vec[index] << endl;
    }

    for (i = 0; i < n; i++) {
        delete str_vec[i];
    }

    return true;
}

